<template>
  <div class="system-customerInfo-container">
    <el-card shadow="hover">
      <div class="system-customerInfo-search mb15">
        <el-form :model="tableData.param" ref="queryRef" :inline="true" label-width="100px">
          <el-row>
            <el-col :span="6" class="colBlock">
              <el-form-item label="客户名称" prop="customerName">
                <el-input v-model="tableData.param.customerName" placeholder="请输入客户名称" clearable
                  @keyup.enter="customerInfoList" />
              </el-form-item>
            </el-col>
            <el-col :span="6" class="colBlock">
              <el-form-item label=" 联系人" prop="contactPerson">
                <el-input v-model="tableData.param.contactPerson" placeholder="请输入联系人" clearable
                  @keyup.enter="customerInfoList" />
              </el-form-item>
            </el-col>
            <el-col :span="6" class="colBlock">
              <el-form-item label=" 联系电话" prop="contactPhone">
                <el-input v-model="tableData.param.contactPhone" placeholder="请输入联系电话" clearable
                  @keyup.enter="customerInfoList" />
              </el-form-item>
            </el-col>
            <el-col :span="6" class="colBlock">
              <el-form-item>
                <el-button type=" primary" @click="customerInfoList"><el-icon><ele-Search /></el-icon>搜索</el-button>
                <el-button @click="resetQuery(queryRef)"><el-icon><ele-Refresh /></el-icon>重置</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" @click="handleAdd"
              v-auth="'api/v1/equip/customerInfo/add'"><el-icon><ele-Plus /></el-icon>新增</el-button>
          </el-col>
        </el-row>
      </div>
      <el-table v-loading="loading" :data="tableData.data" @selection-change="handleSelectionChange">
        <!-- <el-table-column label="序号" align="center" prop="id" min-width="70px" /> -->
        <el-table-column label="客户编号" align="center" prop="customerId" min-width="150px" />
        <el-table-column label="客户名称" align="center" prop="customerName" min-width="150px" />
        <el-table-column label="联系人" align="center" prop="contactPerson" min-width="150px" />
        <el-table-column label="联系电话" align="center" prop="contactPhone" min-width="150px" />
        <el-table-column label="状态" align="center" prop="customerStatus" min-width="150px" :formatter="statusFormat"/>
        <el-table-column label="省份" align="center" :formatter="(row)=>getDistirectName(row.customerProvince)" prop="customerProvince"
          min-width="150px" />
        <el-table-column label="市" align="center" :formatter="(row)=>getDistirectName(row.customerCity)" prop="customerCity" min-width="150px" />
        <el-table-column label="区县" align="center" :formatter="(row)=>getDistirectName(row.customerCounty)" prop="customerCounty" min-width="150px" />
        <el-table-column label="地址" align="center" prop="customerAddress" min-width="150px" />

        <el-table-column label="创建时间" align="center" prop="createdAt" min-width="150px">
          <template #default="scope">
            <span>{{ proxy.parseTime(scope.row.createdAt, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding" min-width="160px" fixed="right">
          <template #default="scope">
            <el-button type="primary" link @click="handleUpdate(scope.row)"
              v-auth="'api/v1/equip/customerInfo/edit'"><el-icon><ele-EditPen /></el-icon>修改</el-button>
            <el-button type="primary" link @click="handleDelete(scope.row)"
              v-auth="'api/v1/equip/customerInfo/del'"><el-icon><ele-Delete /></el-icon>删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="tableData.total > 0" :total="tableData.total" v-model:page="tableData.param.pageNum"
        v-model:limit="tableData.param.pageSize" @pagination="customerInfoList" />
    </el-card>
    <ApiV1SystemCustomerInfoEdit ref="editRef" @customerInfoList="customerInfoList"></ApiV1SystemCustomerInfoEdit>
  </div>
</template>
<script>
import { toRefs, reactive, onMounted, ref, defineComponent, computed, getCurrentInstance, toRaw } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import {
  listCustomerInfo,
  getCustomerInfo,
  delCustomerInfo,
  addCustomerInfo,
  updateCustomerInfo,
} from "../../api/customer";
import ApiV1SystemCustomerInfoEdit from "./edit.vue"
import { getDistirectName } from '/@/components/CitySelector/utils'
import lodash from 'lodash'
export default defineComponent({
  name: "ApiV1SystemCustomerInfoList",
  components: {
    ApiV1SystemCustomerInfoEdit,
  },
  setup() {
    const { proxy } = getCurrentInstance()
    const loading = ref(false)
    const queryRef = ref()
    const editRef = ref();
    const detailRef = ref();
    // 是否显示所有搜索选项
    const showAll = ref(true)
    // 非单个禁用
    const single = ref(true)
    // 非多个禁用
    const multiple = ref(true)
    const word = computed(() => {
      if (showAll.value === false) {
        //对文字进行处理
        return "展开搜索";
      } else {
        return "收起搜索";
      }
    })
    // 字典选项数据        
    const {
      customer_status
    } = proxy.useDict(
      'customer_status'
    )
    // 标签字典翻译
    const statusFormat = (row) => {
      return proxy.selectDictLabel(customer_status.value, row.customerStatus);
    }
    const state = reactive({
      ids: [],
      tableData: {
        data: [],
        total: 0,
        loading: false,
        param: {
          pageNum: 1,
          pageSize: 10,
          id: undefined,
          customerId: undefined,
          customerName: undefined,
          contactPerson: undefined,
          contactPhone: undefined,
          customerProvince: undefined,
          customerCity: undefined,
          customerCounty: undefined,
          customerAddress: undefined,
          customerStatus: undefined,
          tenantId: undefined,
          tenantName: undefined,
          createdBy: undefined,
          createdAt: undefined,
          dateRange: [],
        },
      },
    });
    // 页面加载时
    onMounted(() => {
      initTableData();
    });
    // 初始化表格数据
    const initTableData = () => {
      customerInfoList()
    };
    /** 重置按钮操作 */
    const resetQuery = (formEl) => {
      if (!formEl) return
      formEl.resetFields()
      customerInfoList()
    };
    // 获取列表数据
    const customerInfoList = () => {
      loading.value = true
      listCustomerInfo(state.tableData.param).then((res) => {
        let list = res.data.list ?? [];
        list.map((item) => {
          item.createdBy = item.createdUser?.userNickname
        })
        state.tableData.data = list;
        state.tableData.total = res.data.total;
        loading.value = false
      })
    };
    const toggleSearch = () => {
      showAll.value = !showAll.value;
    }
    // 多选框选中数据
    const handleSelectionChange = (selection) => {
      state.ids = selection.map(item => item.id)
      single.value = selection.length != 1
      multiple.value = !selection.length
    }
    const handleAdd = () => {
      editRef.value.openDialog()
    }
    const handleUpdate = (row) => {
      if (!row) {
        row = state.tableData.data.find((item) => {
          return item.id === state.ids[0]
        })
      }
      editRef.value.openDialog(toRaw(row));
    };
    const handleDelete = (row) => {
      console.log("row",row);
      let msg = '你确定要删除所选数据？';
      let id = [];
      if (row) {
        msg = `此操作将永久删除数据，是否继续?`
        id = [row.id]
      } else {
        id = state.ids
      }
      if (id.length === 0) {
        ElMessage.error('请选择要删除的数据。');
        return
      }
      ElMessageBox.confirm(msg, '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          const customer_id = lodash.get(row,'customerId','')
          delCustomerInfo({customer_id}).then(() => {
            ElMessage.success('删除成功');
            customerInfoList();
          })
        })
        .catch(() => { });
    }
    return {
      getDistirectName,
      customer_status,
      statusFormat,
      proxy,
      editRef,
      detailRef,
      showAll,
      loading,
      single,
      multiple,
      word,
      queryRef,
      resetQuery,
      customerInfoList,
      toggleSearch,
      handleSelectionChange,
      handleAdd,
      handleUpdate,
      handleDelete,
      ...toRefs(state),
    }
  }
})
</script>
<style lang="scss" scoped>
.colBlock {
  display: block;
}

.colNone {
  display: none;
}

.ml-2 {
  margin: 3px;
}
</style>